#include "widget.h"
#include "ui_widget.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QSqlDatabase>
#include <QMessageBox>
#include <QSqlTableModel>
#include <QSqlQuery>
#include <QApplication>
#include <QMessageBox>
#include <QDesktopWidget>

// Widget类的构造函数
Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    // 设置背景图片
    QPixmap pixmap(":/R-C.jpg");
    QPalette palette;
    palette.setBrush(backgroundRole(), QBrush(pixmap));
    setPalette(palette);
    setAutoFillBackground(true);

    // 初始化MQTT客户端
    pMqttClient = new QMqttClient(this);

    // 设置窗口标题
    this->setWindowTitle("农业环境监测系统");

    // 设置默认值
    ui->username->setText("hdx");
    ui->password->setText("123456");
    ui->ip->setText("47.115.61.207");
    ui->port->setText("1883");
    ui->topic2->setText("/topic/089");

    // 连接MQTT客户端的信号和槽
    connect(pMqttClient, &QMqttClient::stateChanged, this, &Widget::updateLogStateChange);
    connect(pMqttClient, &QMqttClient::messageReceived, this, &Widget::recv_message);
}

// Widget类的析构函数
Widget::~Widget()
{
    delete ui;
}

// 更新日志状态变化
void Widget::updateLogStateChange()
{
    const QString content = QLatin1String(": State Change")
                    + QString::number(pMqttClient->state())
                    + QLatin1Char('\n');
    qDebug() << content;
}

// 发布消息按钮的槽函数
void Widget::on_pushButton_clicked()
{
    QString topic = ui->topic->text().trimmed();
    QString payload = ui->payload->text().trimmed();
    pMqttClient->publish(QMqttTopicName(topic), payload.toLocal8Bit());
    qDebug() << "publish:[" << topic << "] " << payload;
}

// 订阅按钮的槽函数
void Widget::on_pushButton_2_clicked()
{
    QString topic = ui->topic2->text().trimmed();
    pMqttClient->subscribe(QMqttTopicFilter(topic));
    qDebug() << "Subscribe:" << topic;
}

// 接收消息的槽函数
void Widget::recv_message(const QByteArray &message, const QMqttTopicName &topic)
{
    // 接收消息
    QString receiveTempStr = ui->recvMessage->toPlainText();
    QString receiveStr = receiveTempStr + "\n[" + topic.name() + "] " + message;
    ui->recvMessage->setPlainText(receiveStr);
    ui->recvMessage->moveCursor(QTextCursor::End);
    qDebug() << message << "\n" << topic.name();

    // 如果主题是"/topic/sensor"，解析JSON数据
    if (topic.name() == "/topic/sensor") {
        QJsonObject json = QJsonDocument::fromJson(message).object();
        QString lux = json["lux"].toString();
        QString temp = json["temp"].toString();
        QString humid = json["humid"].toString();
        QString adc1 = json["adc1"].toString();
        QString adc2 = json["adc2"].toString();

        // 将解析后的数据显示在界面上
        ui->lux->setText(lux);
        ui->temp->setText(temp);
        ui->humid->setText(humid);
        ui->adc1->setText(adc1);
        ui->adc2->setText(adc2);

        qDebug() << "temp:" << temp << " humid:" << humid;

        // 连接数据库
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
        db.setDatabaseName("/home/hr/sg.db");
        if (!db.open()) {
            QMessageBox::information(this, "连接结果", "连接数据库失败!");
            return;
        }

        // 插入数据到数据库
        QSqlQuery query;
        query.prepare("insert into sensor(lux,temp,humid,adc1,adc2) values(:lux,:temp, :humid, :adc1, :adc2)");
        query.bindValue(":lux", lux);
        query.bindValue(":temp", temp);
        query.bindValue(":humid", humid);
        query.bindValue(":adc1", adc1);
        query.bindValue(":adc2", adc2);
        query.exec();
        db.close();
    }
}

// 连接/断开MQTT服务器按钮的槽函数
void Widget::on_pushButton_3_clicked()
{
    QString topic = ui->topic2->text().trimmed();
    pMqttClient->subscribe(QMqttTopicFilter(topic));
    qDebug() << "Subscribe:" << topic;

    pMqttClient->setHostname(ui->ip->text().trimmed());
    pMqttClient->setPort(ui->port->text().trimmed().toUInt());
    pMqttClient->setUsername(ui->username->text().trimmed());
    pMqttClient->setPassword(ui->password->text().trimmed());

    updateLogStateChange();
    if (pMqttClient->state() == QMqttClient::Disconnected) {
        pMqttClient->connectToHost();
        ui->pushButton_3->setText(tr("Disconnect"));
        pMqttClient->subscribe(QMqttTopicFilter("/topic/sensor"));
    } else {
        pMqttClient->disconnectFromHost();
        ui->pushButton_3->setText(tr("Connect"));
    }
}

// 查询数据库按钮的槽函数
void Widget::on_pushButton_4_clicked()
{
    // 连接数据库
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName("/home/hr/sg.db");
    if (!db.open()) {
        QMessageBox::information(this, "连接结果", "连接数据库失败!");
        return;
    }

    // 查询最近的5条数据
    QSqlQuery query;
    query.exec("select id,lux,temp,humid,adc1,adc2 from sensor order by id desc limit 5 offset 0;");
    QString receiveStr = "";
    while (query.next()) {
        QString id = query.value(0).toString();
        QString lux = query.value(1).toString();
        QString temp = query.value(2).toString();
        QString humid = query.value(3).toString();
        QString adc1 = query.value(4).toString();
        QString adc2 = query.value(5).toString();
        qDebug() << id << temp << humid << adc1 << adc2;
        receiveStr += "\nid=" + id + "  lux=" + lux + "  temp=" + temp + "  humid=" + humid + "\n"
                      + "  adc1=" + adc1 + "  adc2=" + adc2 + "\n" + "———————————————————";
    }
    ui->sensors->setPlainText(receiveStr);
    ui->sensors->moveCursor(QTextCursor::End);
    db.close();
}

// 发布控制消息按钮的槽函数
void Widget::on_control_clicked()
{
    QString topic = ui->topic->text().trimmed();
    QString payload = ui->controljson->text().trimmed();
    pMqttClient->publish(QMqttTopicName(topic), payload.toLocal8Bit());
    qDebug() << "publish:[" << topic << "] " << payload;
}

// 发布阈值消息按钮的槽函数
void Widget::on_set_clicked()
{
    QString topic = ui->topic->text().trimmed();
    QString payload = ui->threshold->text().trimmed();
    pMqttClient->publish(QMqttTopicName(topic), payload.toLocal8Bit());
    qDebug() << "publish:[" << topic << "] " << payload;
}
